package main.old.new_2023.last.month_6;

/**
 * @Description:
 * //TODO 13. 最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * @Author: Take-off
 * @Date: 1:00 PM 2023/6/4
 * @Param:
 * @return:
 **/

public class Solution0604_2 {
    //最长公共前缀
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0){
            return  "";
        }
        String prefix = strs[0];
        for (int i =1;i < strs.length;i++){
            String nextPrefix = strs[i];
            prefix = getPrefix(prefix, nextPrefix);
            if (prefix.equals("")){
                break;
            }
        }
        return prefix;
    }

    private String getPrefix( String prefix,String nextPrefix){
        String max= "";
        int minLength = Math.min(prefix.length(), nextPrefix.length());
        for (int i =0;i<minLength ;i++){
            if (prefix.charAt(i) == nextPrefix.charAt(i)){
                max = max + prefix.charAt(i);
            }else {
                break;
            }
        }
        return max;
    }



    public static void main(String[] args) {
        String[] nums = {"ab", "a"};
        Solution0604_2 solu = new Solution0604_2();
        String s = solu.longestCommonPrefix(nums);
        System.out.println(s);

    }

}
